/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package cn.yzc;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * <p>Project: RabbitMQ - Publisher</p>
 * <p>Powered by yzc On 2023-12-19 15:51:27</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */

/**
 * 生产者
 */
public class Publisher {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置虚拟机的名称
        factory.setVirtualHost("/");
        //用户名
        factory.setUsername("admin");
        //密码
        factory.setPassword("5672");
        //设置端口好
        factory.setPort(5672);
        //设置mq服务器地址
        factory.setHost("127.0.0.1");

        //2.创建连接
        Connection conn = factory.newConnection();

        //3.创建信道
        Channel channel = conn.createChannel();

       //4.声明延迟交换器
        String ex = "lazy-ex";
        Map<String,Object> map = new HashMap<>();
        map.put("x-delayed-type","direct");//指明交换器类型
        /**
         * @Param exchange - 交换器名称
         * @Param type - 交换器类型 这里为 x-delayed-message
         * @Param durable - 交换器是否持久化
         * @Param autoDelete - 交换器是否自动删除
         * @Param arguments - 参数
         */
        channel.exchangeDeclare(ex,"x-delayed-message",true,false,map);

        //5.声明延时队列
        String qname = "lazyQueue";
        channel.queueDeclare(qname,true,false,false,null);

        //6.绑定交换器和队列
        channel.queueBind(qname,ex,"lazy");

        //7.发送消息
        Map<String,Object> header = new HashMap<>();
        header.put("x-delay",10000); //延迟10s后 发送到队列
        AMQP.BasicProperties prop = new AMQP.BasicProperties()
                .builder()
                        .headers(header)
                                .build();
        channel.basicPublish(ex,"lazy",prop,"你好啊".getBytes(StandardCharsets.UTF_8));

        //6.关闭连接 释放资源
        conn.close();

        System.out.println("消息发送完毕.....");

    }
}
